package com.os.core.exception;

import com.os.core.common.JsonResult;
import com.os.core.common.ResultCode;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述:
 *
 * @author Matt
 * @create 2021-05-30 17:18
 */
@RestControllerAdvice
public class OsAjaxExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest req, HttpServletResponse rsp, Exception e) throws Exception{

        e.printStackTrace();

        if(isAjax(req)){
            return rsp;
        }else{
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("exception", e);
            modelAndView.addObject("url", req.getRequestURL());
            modelAndView.setViewName(DEFAULT_ERROR_VIEW);
            return JsonResult.returnResponse(false, ResultCode.SERVICE_ERR, e.getMessage());
        }
    }

    /**
     * 判断是否是Ajax请求
     * @param req
     * @return
     */
    public static boolean isAjax(HttpServletRequest req){
        return  (req.getHeader("X-Requested-With")) != null
                &&
                "XMLHttpRequest".equals(req.getHeader("X-Requested-With").toString());
    }


}
